﻿using AutoMapper;
using Humanizer;
using Outpatient.Doman.Hospitalization;
using Outpatient.Doman.SmartClinic;
using Outpatient.ErrorCode;
using Outpatient.Infrastructure;
using OutpatientApi.DTO;
using OutpatientApi.Methodimplementation.IServices;
using System.Text;

namespace OutpatientApi.Methodimplementation.Services
{
    /// <summary>
    /// 实现药品管理接口
    /// </summary>
    public class PharmacymanagementServices: IPharmacymanagementServices 
    {
        private readonly ILogger<PharmacymanagementServices> logger;
        private readonly IBaseRepository<MedicalCardRegistration> medicalCardRegistration;
        private readonly IBaseRepository<Medicine> medicineRepository;
        private readonly IMapper mapper;

        public PharmacymanagementServices(ILogger<PharmacymanagementServices> logger, 
            IBaseRepository<MedicalCardRegistration> medicalCardRegistration,
            IBaseRepository<Medicine> medicineRepository,
            IMapper mapper)
        {
            this.logger = logger;
            this.medicalCardRegistration = medicalCardRegistration;
            this.medicineRepository = medicineRepository;
            this.mapper = mapper;
        }


        /// <summary>
        /// 未打单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<PharmacyDto>>> GetPharmacymanagement(GetPharmacymanagementDto dto)
        {
            try
            {
                var res = new ApiResult<List<PharmacyDto>>();

                var info = medicalCardRegistration.Getlist().Where(x => x.IsDelete.Equals(false) && x.Dadan.Equals(false)).Select(x=>new PharmacyDto()
                {
                    MedicalCardRegistrationId=x.MedicalCardRegistrationId,
                    Card_number=x.Card_number,
                    Name=x.Name,
                    Gender=x.Gender,
                    Age=x.Age,
                    IDNumber=x.IDNumber
                }).ToList();

                if (!string.IsNullOrEmpty(dto.Card_number))
                {
                    info = info.Where(x => x.Card_number.Equals(dto.Card_number)).ToList();
                }
                if (!string.IsNullOrEmpty(dto.Name))
                {
                    info = info.Where(x => x.Name.Equals(dto.Name)).ToList();
                }

                res.success(info, "未打单信息查找成功");
                return res;



            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 已打单未发药
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<PharmacyDto>>> Themedicinehasnotbeenissued(GetPharmacymanagementDto dto)
        {
            try
            {
                var res = new ApiResult<List<PharmacyDto>>();

                var info = medicalCardRegistration.Getlist().Where(x => x.IsDelete.Equals(false) && x.Dadan.Equals(true)&&x.Fayao.Equals(false)).Select(x => new PharmacyDto()
                {
                    MedicalCardRegistrationId = x.MedicalCardRegistrationId,
                    Card_number = x.Card_number,
                    Name = x.Name,
                    Gender = x.Gender,
                    Age = x.Age,
                    IDNumber = x.IDNumber
                }).ToList();

                if (!string.IsNullOrEmpty(dto.Card_number))
                {
                    info = info.Where(x => x.Card_number.Equals(dto.Card_number)).ToList();
                }
                if (!string.IsNullOrEmpty(dto.Name))
                {
                    info = info.Where(x => x.Name.Equals(dto.Name)).ToList();
                }

                res.success(info, "未打单信息查找成功");
                return res;



            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 实现发药功能
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> Dispensing_medicine(int MedicalCardRegistrationId)
        {
            try
            {
                var res = new ApiResult();

                var info = await medicalCardRegistration.GetValue(x => x.MedicalCardRegistrationId.Equals(MedicalCardRegistrationId));
                if (info != null)
                {
                    info.Fayao= true;

                    var model = await medicalCardRegistration.Update(info);

                    if (model > 0)
                    {
                        res.success("发药成功");
                        return res;
                    }
                }

                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 实现打单功能
        /// </summary>
        /// <param name="MedicalCardRegistrationId">医疗卡注册ID</param>
        /// <returns></returns>
        public async Task<ApiResult> PrintPrescription(int MedicalCardRegistrationId)
        {
            try
            {
                var res = new ApiResult();

                // 根据ID查找对应的医疗卡注册信息
                var info = await medicalCardRegistration.GetValue(x => x.MedicalCardRegistrationId.Equals(MedicalCardRegistrationId));
                
                if (info == null)
                {
                    res.msg = "未找到对应的医疗卡注册信息";
                    res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                    return res;
                }

                // 检查是否已经打单
                if (info.Dadan == true)
                {
                    res.msg = "该处方已经打单，无需重复操作";
                    res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                    return res;
                }

                // 记录打单日志
                logger.LogInformation("开始打单，患者信息：姓名={Name}，卡号={Card_number}，身份证号={IDNumber}", 
                    info.Name, info.Card_number, info.IDNumber);

                // 更新打单状态为true
                info.Dadan = true;
                var model = await medicalCardRegistration.Update(info);

                if (model > 0)
                {
                    logger.LogInformation("打单成功，患者：{Name}，卡号：{Card_number}", info.Name, info.Card_number);
                    res.success("打单成功");
                    return res;
                }
                else
                {
                    res.msg = "打单失败，请重试";
                    res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                    return res;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "打单操作失败，MedicalCardRegistrationId：{MedicalCardRegistrationId}", MedicalCardRegistrationId);
                var res = new ApiResult();
                res.msg = "打单操作失败";
                res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                return res;
            }
        }

        /// <summary>
        /// 查找已发药品信息
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<PharmacyDto>>> GeuData()
        {
            try
            {
                var res = new ApiResult<List<PharmacyDto>>();

                var info = medicalCardRegistration.Getlist().Where(x => x.IsDelete.Equals(false) && x.Fayao.Equals(true)).Select(x => new PharmacyDto()
                {
                    MedicalCardRegistrationId = x.MedicalCardRegistrationId,
                    Card_number = x.Card_number,
                    Name = x.Name,
                    Gender = x.Gender,
                    Age = x.Age,
                    IDNumber = x.IDNumber
                }).ToList();


                res.success(info, "未打单信息查找成功");
                return res;



            }
            catch (Exception)
            {

                throw;
            }

        }


        /// <summary>
        /// 药品查找方法
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns></returns>
        public async Task<ApiResult<List<MedicineDto>>> SearchMedicine(SearchMedicineDto dto)
        {
            var res = new ApiResult<List<MedicineDto>>();

            try
            {
                // 获取所有未删除的药品
                var medicines = medicineRepository.Getlist().Where(x => !x.IsDelete).ToList();

                // 根据查询条件过滤
                if (!string.IsNullOrEmpty(dto.MedicineName))
                {
                    medicines = medicines.Where(x => x.MedicineName.Contains(dto.MedicineName)).ToList();
                }

                if (dto.MedicinePrice.HasValue)
                {
                    medicines = medicines.Where(x => x.SellingPrice == dto.MedicinePrice.Value).ToList();
                }

                if (!string.IsNullOrEmpty(dto.DosageForm))
                {
                    medicines = medicines.Where(x => x.DosageForm.Contains(dto.DosageForm)).ToList();
                }

                if (dto.PurchasePrice.HasValue)
                {
                    medicines = medicines.Where(x => x.PurchasePrice == dto.PurchasePrice.Value).ToList();
                }

                if (dto.SellingPrice.HasValue)
                {
                    medicines = medicines.Where(x => x.SellingPrice == dto.SellingPrice.Value).ToList();
                }

                // 转换为DTO
                var result = medicines.Select(x => new MedicineDto
                {
                    MedicineId = x.MedicineId,
                    AdmissionId = x.AdmissionId,
                    MedicineName = x.MedicineName,
                    DrugType = x.DrugType,
                    FeeName = x.FeeName,
                    DosageForm = x.DosageForm,
                    Specification = x.Specification,
                    PurchasePrice = x.PurchasePrice,
                    SellingPrice = x.SellingPrice,
                    StockQuantity = x.StockQuantity,
                    StockUpperLimit = x.StockUpperLimit,
                    StockLowerLimit = x.StockLowerLimit,
                    ProductionDate = x.ProductionDate,
                    ExpirationDate = x.ExpirationDate,
                    Efficacy = x.Efficacy
                }).ToList();

                res.success(result, "药品查找成功");
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "药品查找失败");
                res.msg = "药品查找失败";
                res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                return res;
            }
        }

        /// <summary>
        /// 药品出库方法
        /// </summary>
        /// <param name="medicineId">药品ID</param>
        /// <returns></returns>
        public async Task<ApiResult<object>> MedicineOutbound(int medicineId)
        {
            var res = new ApiResult<object>();
            
            try
            {
                // 根据药品ID查找对应数据
                var medicine = medicineRepository.Getlist().FirstOrDefault(x => x.MedicineId == medicineId && !x.IsDelete);
                
                if (medicine == null)
                {
                    res.msg = "药品不存在或已被删除";
                    res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                    return res;
                }

                // 执行删除操作（逻辑删除）
                medicine.IsDelete = true;
                medicineRepository.Update(medicine);

                res.success(null, "药品出库成功");
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "药品出库失败");
                res.msg = "药品出库失败";
                res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                return res;
            }
        }
        /// <summary>
        /// 药品入库
        /// </summary>
        /// <param name="dto">药品信息</param>
        /// <returns></returns>
        public async Task<ApiResult> Create_medicines(Create_medicinesDto dto)
        {
            try
            {
                var res = new ApiResult();

                var info = mapper.Map<Medicine>(dto);

                info.AdmissionId = 1;

                var model = await medicineRepository.AddAsyn(info);

                if (model > 0)
                {
                    res.success("入库成功");
                    return res;
                }

                return res;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "药品入库失败");
                var res = new ApiResult();
                res.msg = "药品入库失败";
                res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                return res;
            }
        }

        /// <summary>
        /// 修改药品信息
        /// </summary>
        /// <param name="dto">修改的药品信息</param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateMedicine(UpdateMedicineDto dto)
        {
            try
            {
                var res = new ApiResult();

                // 根据ID查找药品
                var existingMedicine = medicineRepository.Getlist().FirstOrDefault(x => x.MedicineId == dto.MedicineId && !x.IsDelete);
                
                if (existingMedicine == null)
                {
                    res.msg = "药品不存在或已被删除";
                    res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                    return res;
                }

                // 更新药品信息
                existingMedicine.MedicineName = dto.MedicineName;
                existingMedicine.DrugType = dto.DrugType;
                existingMedicine.FeeName = dto.FeeName;
                existingMedicine.DosageForm = dto.DosageForm;
                existingMedicine.Specification = dto.Specification;
                existingMedicine.PurchasePrice = dto.PurchasePrice;
                existingMedicine.SellingPrice = dto.SellingPrice;
                existingMedicine.StockQuantity = dto.StockQuantity;
                existingMedicine.StockUpperLimit = dto.StockUpperLimit;
                existingMedicine.StockLowerLimit = dto.StockLowerLimit;
                existingMedicine.ProductionDate = dto.ProductionDate;
                existingMedicine.ExpirationDate = dto.ExpirationDate;
                existingMedicine.Efficacy = dto.Efficacy;

                // 保存更新
                var result = await medicineRepository.Update(existingMedicine);

                if (result > 0)
                {
                    res.success("药品信息修改成功");
                    return res;
                }
                else
                {
                    res.msg = "药品信息修改失败";
                    res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                    return res;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "药品信息修改失败");
                var res = new ApiResult();
                res.msg = "药品信息修改失败";
                res.code = Outpatient.ErrorCode.ApiREunm.Fail;
                return res;
            }
        }


    }
}
